package com.sg.business.model.bpmservice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mobnut.db.model.IContext;
import com.mobnut.db.model.ModelService;
import com.mobnut.db.model.PrimaryObject;
import com.mongodb.DBObject;
import com.sg.bpm.service.task.ServiceProvider;
import com.sg.bpm.workflow.utils.WorkflowUtils;
import com.sg.business.model.Document;
import com.sg.business.model.IEngineeringChange;
import com.sg.business.model.Work;
import com.sg.widgets.MessageUtil;

public class EngineeringChangeService extends ServiceProvider {

	@Override
	public Map<String, Object> run(Object parameter) {
		HashMap<String, Object> result = new HashMap<String, Object>();
		Object content = getInputValue("content"); //$NON-NLS-1$
		if (content instanceof String) {
			String jsonContent = (String) content;
			PrimaryObject host = WorkflowUtils.getHostFromJSON(jsonContent);
			if (host instanceof Work) {
				Work work = (Work) host;
				DBObject processData = WorkflowUtils
						.getProcessInfoFromJSON(jsonContent);
				String processId = (String) processData.get("processId"); //$NON-NLS-1$
				String processName = (String) processData.get("processName"); //$NON-NLS-1$
				IContext context = new BPMServiceContext(processName, processId);
				List<?> worklist = work
						.getListValue(IEngineeringChange.F_WORKLIST);
				for (Object obj : worklist) {
					if (obj instanceof DBObject) {
						doCreateWork((DBObject) obj, work, context);
					}
				}
			}
		}

		return result;
	}

	private void doCreateWork(DBObject obj, Work parentWork, IContext context) {
		Work work = ModelService.createModelObject(obj, Work.class);
		try {
			work.setValue(Work.F_PARENT_ID, parentWork.get_id());
			work.setValue(Work.F_WORK_TYPE, Work.WORK_TYPE_STANDLONE);
			work.doSaveAndSaveDeli(context);
			List<PrimaryObject> documents = work
					.getOutputDeliverableDocuments();
			for (PrimaryObject po : documents) {
				((Document) po).doUpdateVersion();
			}
		} catch (Exception e) {
			MessageUtil.showToast(e);
		}
	}

}
